package com.persondemo.videoappliction.ui.movie;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.MainBean;
import com.persondemo.videoappliction.bean.TvMovieBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.event.GridEvent;
import com.persondemo.videoappliction.ui.adapter.BaseVideoAdapter;
import com.persondemo.videoappliction.ui.adapter.MoiveAgeAdapter;
import com.persondemo.videoappliction.ui.adapter.MoiveTypeAdapter;
import com.persondemo.videoappliction.ui.adapter.MovieCityAdapter;
import com.persondemo.videoappliction.ui.adapter.RecyclerAdapter;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.base.BaseFragment;
import com.persondemo.videoappliction.ui.movie.contract.MoiveContract;
import com.persondemo.videoappliction.ui.movie.presenter.MoviePresenter;
import com.persondemo.videoappliction.ui.search.SearchActivity;
import com.persondemo.videoappliction.ui.video.VideoDetilsActivity;
import com.persondemo.videoappliction.ui.video.WeBviewActivity;
import com.persondemo.videoappliction.utils.AnimationUtil;
import com.persondemo.videoappliction.utils.ImageLoaderUtil;
import com.persondemo.videoappliction.utils.RxDeviceTool;
import com.persondemo.videoappliction.utils.T;
import com.persondemo.videoappliction.utils.ViewFindUtils;
import com.persondemo.videoappliction.widget.CustomLoadMoreView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by Administrator on 2018/3/20.
 */
public class MovieActivity extends BaseActivity<MoviePresenter> implements MoiveContract.View {
    public static final String TAG = "MovieActivity";
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;
    RecyclerAdapter ad;
    @BindView(R.id.zuire)
    TextView zuire;
    @BindView(R.id.zuixin)
    TextView zuixin;
    @BindView(R.id.haoping)
    TextView haoping;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.rl_movie_type)
    RelativeLayout rlMovieType;
    @BindView(R.id.SimpleMultiStateView)
    com.persondemo.videoappliction.widget.SimpleMultiStateView SimpleMultiStateView;
    @BindView(R.id.mPtrFrameLayout)
    PtrClassicFrameLayout mPtrFrameLayout;
    Unbinder unbinder;
    @BindView(R.id.movie_title)
    TextView movieTitle;
    Unbinder unbinder1;
    private RecyclerView recycle_01;
    private RecyclerView recycle_02;
    private RecyclerView recycle_03;
    private MoiveTypeAdapter typeadapter;
    private MoiveAgeAdapter agedapter;
    private MovieCityAdapter citydapter;
    private BaseVideoAdapter baseVideoAdapter;
    private PopupWindow window;
    int fromYDelta;
    List<TvMovieBean.DataBean.TypesListBean> typelist = new ArrayList<>();//电影类型
    List<TvMovieBean.DataBean.AgesListBean> agelist = new ArrayList<>();//地区名字
    List<TvMovieBean.DataBean.CityListBean> citylist = new ArrayList<>();//年代
    List<TvMovieBean.DataBean.DylistBean> dylistBeanList = new ArrayList<>();
    List<TvMovieBean.DataBean.AdfListBean> adfListBeanList = new ArrayList<>();//广告
    private static final String TYPE = "1";//类型
    private String types = "";//电影类型
    private String city = "";//地区名字
    private String ages = "";//年代
    private int page = 1;//页数
    private Banner banner;
    View headview, footview;
    private TextView foot_version;

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public int getContentLayout() {
        return R.layout.module_fragment_movie;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void bindView(View view, Bundle savedInstanceState) {

//        EventBus.getDefault().register(this);
        headview = LayoutInflater.from(this).inflate(R.layout.module_include_banner, null);
        footview = LayoutInflater.from(this).inflate(R.layout.footview, null);
        foot_version = footview.findViewById(R.id.foot_version);
        foot_version.setText("当前版本：" + RxDeviceTool.getVerName(this));
        banner = headview.findViewById(R.id.banner);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        //Glide 加载图片简单用法
                        ImageLoaderUtil.LoadImage(MovieActivity.this, path, imageView);
                    }
                })
                .setDelayTime(3000)
                .setIndicatorGravity(BannerConfig.RIGHT);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (adfListBeanList != null && adfListBeanList.size() > 0) {
                    if (adfListBeanList.get(position).getUrl().contains("http")) {
                        Intent intent = new Intent(MovieActivity.this, WeBviewActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("title", adfListBeanList.get(position).getUrl());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        gotovideodetils(Integer.parseInt(adfListBeanList.get(position).getUrl()));
                    }
                }
            }
        });
        mPtrFrameLayout.disableWhenHorizontalMove(true);
        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mRecyclerView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                if (mPresenter != null) {
                    types = "";//电影类型
                    city = "";//地区名字
                    ages = "";//年代
                    mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
                }
            }
        });
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        baseVideoAdapter = new BaseVideoAdapter(dylistBeanList, MovieActivity.this);
        mRecyclerView.setAdapter(baseVideoAdapter);
        baseVideoAdapter.setEnableLoadMore(true);
        baseVideoAdapter.setLoadMoreView(new CustomLoadMoreView());
        baseVideoAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        baseVideoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                gotovideodetils(dylistBeanList.get(position).getId());
            }
        });
        baseVideoAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
            }
        }, mRecyclerView);
    }

    @Override
    public void initData() {
        showLoadingDialog();
        typelist = new ArrayList<>();
        agelist = new ArrayList<>();
        citylist = new ArrayList<>();
        dylistBeanList = new ArrayList<>();
        Intent intent=getIntent();
        if (intent!=null){
            types=intent.getStringExtra("title");
        }
        if (mPresenter != null) {
            city = "";//地区名字
            ages = "";//年代
            mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
            page++;
        }
    }

    @OnClick({R.id.zuire, R.id.zuixin, R.id.haoping, R.id.rl_movie_type, R.id.rl_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_search:
                startActivity(new Intent(this, SearchActivity.class));
                this.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                break;
            case R.id.zuire:
                setcolor(1);
                break;
            case R.id.zuixin:
                setcolor(2);
                break;
            case R.id.haoping:
                setcolor(3);
                break;
            case R.id.rl_movie_type:

                showpop();
                break;
        }
    }

    private void showpop() {
        View popupView = LayoutInflater.from(this).inflate(R.layout.module_pop_type, null);
        recycle_01 = popupView.findViewById(R.id.recycle_01);
        recycle_02 = popupView.findViewById(R.id.recycle_02);
        recycle_03 = popupView.findViewById(R.id.recycle_03);
        recycle_01.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recycle_02.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recycle_03.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        typeadapter = new MoiveTypeAdapter(typelist, this);
        agedapter = new MoiveAgeAdapter(agelist,  MovieActivity.this);
        citydapter = new MovieCityAdapter(citylist,  MovieActivity.this);
        recycle_01.setAdapter(typeadapter);
        recycle_02.setAdapter(citydapter);
        recycle_03.setAdapter(agedapter);
        typeadapter.setOnItemActionListener(new MoiveTypeAdapter.OnItemActionListener() {
            @Override
            public void onItemClickListener(View v, int pos) {
                types = typelist.get(pos).getId() + "";
                page = 1;
                Log.i("lidamingtypes", "tyes=" + types + "city=" + city + "ages=" + ages + "page=" + page);
                if (mPresenter != null) {
                    showLoadingDialog();
                    mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
                }
            }
        });
        agedapter.setOnItemActionListener(new MoiveAgeAdapter.OnItemActionListener() {
            @Override
            public void onItemClickListener(View v, int pos) {
                ages = agelist.get(pos).getAges();
//                dylistBeanList.clear();
                page = 1;
                Log.i("lidamingages", "tyes=" + types + "city=" + city + "ages=" + ages + "page=" + page);
                if (mPresenter != null) {
                    showLoadingDialog();
                    mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
                }
            }
        });
        citydapter.setOnItemActionListener(new MovieCityAdapter.OnItemActionListener() {
            @Override
            public void onItemClickListener(View v, int pos) {
                city = citylist.get(pos).getCity();
                Log.i("lidamingcity", "tyes=" + types + "city=" + city + "ages=" + ages + "page=" + page);
                page = 1;
                if (mPresenter != null) {
                    showLoadingDialog();
                    mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
                }
            }
        });
        window = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        window.setBackgroundDrawable(new BitmapDrawable());
        //将这两个属性设置为false，使点击popupwindow外面其他地方会消失
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        //获取popupwindow高度确定动画开始位置
        int contentHeight = ViewFindUtils.getViewMeasuredHeight(popupView);
        window.showAsDropDown(rlMovieType, 0, 0);
        fromYDelta = -contentHeight - 50;

        window.getContentView().startAnimation(AnimationUtil.createInAnimation(this, fromYDelta));
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                getlayoutColor();
            }
        });

    }

    private void setcolor(int i) {
        switch (i) {
            case 1:
                zuire.setTextColor(Color.parseColor("#64B6D1"));
                zuixin.setTextColor(Color.parseColor("#ffffff"));
                haoping.setTextColor(Color.parseColor("#ffffff"));
                break;
            case 2:
                zuire.setTextColor(Color.parseColor("#ffffff"));
                zuixin.setTextColor(Color.parseColor("#64B6D1"));
                haoping.setTextColor(Color.parseColor("#ffffff"));
                break;
            case 3:
                zuire.setTextColor(Color.parseColor("#ffffff"));
                zuixin.setTextColor(Color.parseColor("#ffffff"));
                haoping.setTextColor(Color.parseColor("#64B6D1"));
                break;
        }
    }
    @Override
    public void loaddata(TvMovieBean tvMovieBean) {
        if (tvMovieBean == null) {
            showFaild();
            hideLoadingDialog();
            return;
        }
        if (tvMovieBean.getData().getDylist() == null || tvMovieBean.getData().getDylist().size() == 0) {
            hideLoadingDialog();
            T.showShort(this, "没有更多数据了！");
            return;
        }
        if (tvMovieBean.getStatus() == 1) {
            if (tvMovieBean.getData().getTypesList() != null && tvMovieBean.getData().getTypesList().size() > 0) {
                typelist = tvMovieBean.getData().getTypesList();

            }
            if (tvMovieBean.getData().getAgesList() != null && tvMovieBean.getData().getAgesList().size() > 0) {
                agelist = tvMovieBean.getData().getAgesList();

            }
            if (tvMovieBean.getData().getCityList() != null && tvMovieBean.getData().getCityList().size() > 0) {
                citylist = tvMovieBean.getData().getCityList();
            }
            if (tvMovieBean.getData().getDylist() != null && tvMovieBean.getData().getDylist().size() > 0) {
                dylistBeanList.clear();
                baseVideoAdapter.removeAllHeaderView();
                baseVideoAdapter.removeAllFooterView();
                dylistBeanList = tvMovieBean.getData().getDylist();
                baseVideoAdapter.disableLoadMoreIfNotFullPage(mRecyclerView);
                baseVideoAdapter.setNewData(tvMovieBean.getData().getDylist());
                mPtrFrameLayout.refreshComplete();
                showSuccess();
                hideLoadingDialog();
                baseVideoAdapter.addHeaderView(headview);
                page++;
                if (dylistBeanList.size() < 24) {
                    baseVideoAdapter.loadMoreEnd();
                    baseVideoAdapter.addFooterView(footview);
                }
            }
            if (tvMovieBean.getData().getAdfList() != null && tvMovieBean.getData().getAdfList().size() > 0) {
                adfListBeanList.clear();
                adfListBeanList = tvMovieBean.getData().getAdfList();
                List<String> mTitleList = new ArrayList<>();
                List<String> mUrlList = new ArrayList<>();
                for (int i = 0; i < tvMovieBean.getData().getAdfList().size(); i++) {
                    mTitleList.add(tvMovieBean.getData().getAdfList().get(i).getName());
                    mUrlList.add(tvMovieBean.getData().getAdfList().get(i).getPic());
                }
                if (mUrlList.size() > 0) {
                    banner.setImages(mUrlList);
                    banner.setBannerTitles(mTitleList);
                    banner.start();
                }
            }
        } else {
            T.showShort(this, tvMovieBean.getMsg());
        }
    }

    @Override
    public void onRetry() {
        if (mPresenter != null) {
            mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
        }
    }

    @Override
    public void loaddatamore(List<TvMovieBean.DataBean.DylistBean> dylistBeanList) {
        if (dylistBeanList == null || dylistBeanList.size() == 0) {
            baseVideoAdapter.loadMoreEnd();
            baseVideoAdapter.addFooterView(footview);
            T.showShort(this, "没有更多数据了！");
            return;
        } else {
            page++;
            baseVideoAdapter.addData(dylistBeanList);
            baseVideoAdapter.loadMoreComplete();

        }
    }

    private void gotovideodetils(int id) {

        Intent intent = new Intent(this, VideoDetilsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("id", id);
        intent.putExtras(bundle);
        startActivity(intent);
        this.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }


}
